package com.ian.controller;

import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.common.util.ResultMsg;
import com.ian.commons.HttpApiClient;
import com.ian.commons.SendMsgCode;
import com.ian.pojo.PerReg;
import com.ian.pojo.PerUser;
import com.ian.service.PerRegService;
import com.ian.service.PerUserService;
import com.ian.util.RandomName;
import com.ian.vo.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户基本服务
 *
 * @Author IanZy
 * @Date 2020/6/15
 */
@Api("登录、注册、找回密码相关API")
@RestController
public class PerLoginController {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PerUserService perUserService;

    @Autowired
    PerRegService perRegService;

    /**
     * 登录
     *
     * @Author IanZy
     * @Date 2020/6/16
     */
    @ApiOperation("登录")
    @PostMapping(value = "/userLogin", produces = "application/json;charset=UTF-8")
    public ResultMsg userLogin(@RequestBody UserInfo userInfo) {
        String mobile = userInfo.getMobile();
        String pwd = userInfo.getPwd();
        PerUser exitUser = perUserService.findByTel(mobile);
        if (exitUser == null) {
            return ResultMsg.failed("该用户不存在~");
        }
        String exitPwd = perUserService.findPwdByTel(mobile);
        System.out.println("数据库存在的密码：" + exitPwd);
        DigestUtils.md5Hex(pwd);
        String addPwd = Hex.encodeHexString(DigestUtils.md5(pwd), true);
        System.out.println("加密后的密码：" + addPwd);
        if (addPwd.equals(exitPwd)) {
            return ResultMsg.success("登录成功~", mobile);
        }
        return ResultMsg.failed("用户名或密码输入错误，请重新输入~");
    }

    /**
     * 注册验证码
     *
     * @Author IanZy
     * @Date 2020/6/16
     */
    @ApiOperation("注册验证码")
    @GetMapping(value = "/sendRegCode", produces = "application/json;charset=UTF-8")
    public ResultMsg sendRegCode(@RequestParam("mobile") String mobile) {
        if (mobile == null) {
            return ResultMsg.failed("请输入手机号~");
        }
        if (perRegService.findByTel(mobile) != null) {
            return ResultMsg.failed("用户已存在，请重新输入~");
        }
        double codeNum = (Math.random() * 9 + 1) * 100000;
        String codeStr = String.valueOf(codeNum);
        String code = codeStr.substring(0, 6);
        System.out.println(code);
        String name = "用户，";
        ApiResponse response = HttpApiClient.getInstance().尊敬的XX您的验证吗是XXXXSyncMode(code, name, mobile);
        /*
            将消息存入redis缓存中
            60s后过期
         */
        redisTemplate.opsForValue().set(mobile, code);
        redisTemplate.expire(mobile, 60, TimeUnit.SECONDS);
        try {
            System.out.println(SendMsgCode.getResultString(response));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.success("发送成功，请查看短信~", mobile);
    }

    /**
     * 注册
     *
     * @Author IanZy
     * @Date 2020/6/16
     */
    @ApiOperation("注册")
    @PostMapping(value = "/register", produces = "application/json;charset=UTF-8")
    public ResultMsg register(@RequestBody UserInfo userInfo) {
        String mobile = userInfo.getMobile();
        System.out.println("用户输入的手机号：" + mobile);
        List<String> perUserTelList = perRegService.finAll();
        for (String perUserTel : perUserTelList) {
            if (mobile.equals(perUserTel)) {
                return ResultMsg.failed("用户已存在，请登录~");
            }
        }
        String pwd = userInfo.getPwd();
        System.out.println("用户输入的密码：" + pwd);
        DigestUtils.md5(pwd);
        String pwdMD5 = Hex.encodeHexString(DigestUtils.md5(pwd), true);
        System.out.println("加密后的密码：" + pwdMD5);
        System.out.println(redisTemplate.opsForValue().get(mobile));
        //获取redis中验证码信息
        if (redisTemplate.opsForValue().get(mobile) != null) {
            PerUser perUser = new PerUser();
            perUser.setPerUserTel(mobile);
            perUser.setPerUserPwd(pwdMD5);
            perUser.setPerUserAddress("四川省-成都市-高新区");
            String name = new RandomName().getName();
            perUser.setPerUserName(name);
            perUser.setPerUserHeadimg("http://img3.imgtn.bdimg.com/it/u=2194837364,3388051517&fm=26&gp=0.jpg");
            perUser.setPerUserSex("男");
            perUser.setPerUserMoney(8888);
            perUser.setPerUserStatus(1);
            perUserService.insert(perUser);
            PerReg perReg = new PerReg();
            perReg.setPerUserTel(mobile);
            perReg.setPerUserId(perUserService.findByTel(mobile).getPerUserId());
            perReg.setPerUserPwd(pwdMD5);
            perRegService.insert(perReg);
            return ResultMsg.success("注册成功~", mobile);
        }
        return ResultMsg.failed("验证码超时~");
    }

    /**
     * 找回密码验证码
     *
     * @Author IanZy
     * @Date 2020/6/16
     */
    @ApiOperation("找回密码验证码")
    @GetMapping(value = "/sendBackCode", produces = "application/json;charset=UTF-8")
    public ResultMsg sendBackCode(@RequestParam("mobile") String mobile) {
        if (mobile == null) {
            return ResultMsg.failed("请输入手机号~");
        }
        if (perRegService.findByTel(mobile) != null) {
            double codeNum = (Math.random() * 9 + 1) * 100000;
            String codeStr = String.valueOf(codeNum);
            String code = codeStr.substring(0, 6);
            System.out.println(code);
            String name = "用户，";
            ApiResponse response = HttpApiClient.getInstance().尊敬的XX您的验证吗是XXXXSyncMode(code, name, mobile);
        /*
            将消息存入redis缓存中
            60s后过期
         */
            redisTemplate.opsForValue().set(mobile, code);
            redisTemplate.expire(mobile, 60, TimeUnit.SECONDS);
            try {
                System.out.println(SendMsgCode.getResultString(response));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResultMsg.success("发送成功，请查看短信~", mobile);
        }
        return ResultMsg.failed("验证码发送失败，请重新获取~");
    }

    /**
     * 找回密码
     *
     * @Author IanZy
     * @Date 2020/6/16
     */
    @ApiOperation("找回密码")
    @PutMapping(value = "/findPwd", produces = "application/json;charset=UTF-8")
    public ResultMsg findPwd(@RequestBody UserInfo userInfo) {
        String mobile = userInfo.getMobile();
        String pwd = userInfo.getPwd();
        System.out.println("用户输入的手机号：" + mobile);
        System.out.println(redisTemplate.opsForValue().get(mobile));
        if (redisTemplate.opsForValue().get(mobile) != null) {
            DigestUtils.md5(pwd);
            String pwdMD5 = Hex.encodeHexString(DigestUtils.md5(pwd), true);
            System.out.println("MD5加密后的密码：" + pwdMD5);
            PerUser perUserOld = perUserService.findByTel(mobile);
            int oldId = perUserOld.getPerUserId();
            String oldName = perUserOld.getPerUserName();
            String oldSex = perUserOld.getPerUserSex();
            String oldAddress = perUserOld.getPerUserAddress();
            String oldHeadImg = perUserOld.getPerUserHeadimg();
            PerUser perUserNew = new PerUser();
            perUserNew.setPerUserId(oldId);
            perUserNew.setPerUserTel(mobile);
            perUserNew.setPerUserPwd(pwdMD5);
            perUserNew.setPerUserName(oldName);
            perUserNew.setPerUserSex(oldSex);
            perUserNew.setPerUserAddress(oldAddress);
            perUserNew.setPerUserHeadimg(oldHeadImg);
            perUserNew.setPerUserStatus(perUserOld.getPerUserStatus());
            perUserNew.setPerUserMoney(perUserOld.getPerUserMoney());
            perUserService.updateByTel(perUserNew);
            PerReg perRegNew = new PerReg();
            perRegNew.setPerUserId(oldId);
            perRegNew.setPerUserTel(mobile);
            perRegNew.setPerUserPwd(pwdMD5);
            perRegService.updateByTel(perRegNew);
            return ResultMsg.success("修改密码成功~", mobile);
        }
        return ResultMsg.failed("验证码超时~");
    }
}